<template>
    <div>
        <!-- 头部信息 -->
        <div class="head">
            <el-input placeholder="用户名" size="small" style="width: 150px;" v-model="searchObj.username"></el-input>
            <div class="box">
                <el-button type="primary" style="width: 70px;" @click="searchUser">查询</el-button>
                <el-button size="small" @click="clearInput">清空</el-button>
            </div>
        </div>
        <div class="center">
            <el-button type="primary" size="big" @click="addUser">添加</el-button>
            <el-button type="danger" size="big" style="width: 100px;" @click="deleteUsers"
                :disabled="selectedIds.length==0">批量删除</el-button>
        </div>
        <!-- 表格页面 -->
        <el-table @selection-change="handleSelectionChange" :data="users" border style="width: 100%" v-loading="loading"
            element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)">
            <el-table-column type="selection"></el-table-column>
            <el-table-column type="index" label="序号" width="80">
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="130">
            </el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="80">
            </el-table-column>
            <el-table-column prop="roleName" label="角色列表" width="80">
            </el-table-column>
            <el-table-column prop="gmtCreate" label="创建时间" width="180">
            </el-table-column>
            <el-table-column prop="gmtModified" label="更新时间" width="180">
            </el-table-column>
            <el-table-column prop="address" label="操作" align="center">
                <template v-slot="{row,$index}">
                    <el-button type="info" class="el-icon-user" @click="distribute(row)" title="分配角色"></el-button>
                    <el-button type="warning" class="el-icon-edit" @click="editUser(row)" title="修改角色"></el-button>
                    <el-button type="danger" class="el-icon-delete" @click="deleteUser(row)" title="删除角色"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器   -->
        <div>
            <el-pagination @size-change="handleSizeChange" @current-change="getUserList" :current-page="page"
                :page-sizes="[3,5,7]" :page-size="limit" layout=" prev, pager, next, jumper,->,sizes,total"
                :total="total">
            </el-pagination>
        </div>
        <!-- 添加修改对话框 -->
        <el-dialog :title="user.id?'修改用户':'添加用户'" :visible.sync="dialogVisible" width="50%">
            <el-form :model="user" ref="user" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input style="width: 200px;" v-model="user.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input style="width: 200px;" v-model="user.nickName"></el-input>
                </el-form-item>
                <el-form-item v-if="!user.id" prop="password" label="用户密码">
                    <el-input style="width: 200px;" v-model="password"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="getAdd">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="设置角色" :visible.sync="dialoguserFormVisible">
            <el-form :model="role">
                <el-form-item label="用户名" prop="username">
                    <el-input autocomplete="off" v-model="role.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="角色列表" prop="roleList">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                    </el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="item in city" :label="item" :key="item">{{item}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialoguserFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import role from '@/api/acl/role';
export default {
    data() {
        return {
            // 用户列表数据
            users: [],
            page: 1, // 当前页码
            limit: 5, // 每页数量
            total: 0, // 总数量
            selectedIds: [], // 所有选择的user的id的数组 当前要操作的user,
            dialogVisible: false,  //修改添加对话框
            dialoguserFormVisible: false, //分配角色对话框
            // 用户列表每一1项
            user: {
                id: '',
                nickName: '',
                username: '',
            },
            password: '',//用户密码
            searchObj: {
                // input框输入内容
                username: '',
            },

            role: {
                username: '',
                roleList: [],
                assignRoles: [],
                id: ''
            },


            loading: false,
            // 表单验证规则
            rules: {
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 1, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
                ],
                password: [{
                    required: true,
                    min: 5,
                    max: 13,
                    message: '密码长度在 5 到 12 个字符', trigger: 'blur',
                }]
            },

            checkAll: false,
            checkedCities: [], //选中的角色信息
            cities: [],  //角色列表 (包含id 所有信息)
            city: [],//所有的角色名字
            isIndeterminate: true

        }
    },
    mounted() {
        this.getUserList()
    },
    methods: {
        // 获取用户列表
        async getUserList(page) {
            this.loading = true
            this.page = page
            let result = await this.$API.user.getPageList(page, this.limit, this.searchObj)
            this.loading = false
            // console.log(result, 'll');
            this.users = result.data.items
            this.total = result.data.total
        },
        //   修改用户/
        editUser(row) {
            console.log('我是修改')
            this.user = { ...row }
            this.dialogVisible = true
            this.$nextTick(() => {
                this.$refs.user.clearValidate()
            })
        },
        // 添加用户
        addUser() {
            console.log(
                '我是添加'
            );
            this.user.username = ''
            this.user.nickName = ''
            this.user.id = ''
            this.password = ''
            this.$nextTick(() => {
                this.$refs.user.clearValidate()
            })
            this.dialogVisible = true
        },
        //   删除用户
        async deleteUser(row) {
            await this.$API.user.removeById(row.id)
            this.$message({
                type: 'success',
                message: `删除用户${row.username}成功`
            })
            this.getUserList()
            // setTimeout(() => {
            //     window.location.reload()
            // }, 200)
        },
        //  点击对话框确定按钮    
        getAdd() {
            const { user } = this
            user.password = this.password

            this.$refs['user'].validate(async (success) => {
                if (success) {
                    if (user.id) {
                        await this.$API.user.addOrUpdate(user)
                        this.$message({
                            type: 'success',
                            message: '修改用户名成功'
                        })
                    }
                    else {
                        await this.$API.user.addOrUpdate(user)
                        this.$message({
                            type: 'success',
                            message: '添加用户名成功'
                        })
                    }
                    this.dialogVisible = false
                    this.getUserList()
                } else {
                    this.$message()
                    return
                }
            })
        },

        // 点击对话框取消按钮
        cancel() {

            this.dialogVisible = false
        },

        // 点击搜索按钮
        searchUser() {
            this.getUserList()
        },

        // 点击清空按钮
        clearInput() {
            this.searchObj.username = ''
            this.getUserList()
        },

        // 当修改每页数量的监听回调
        handleSizeChange(pageSize) {
            // pageSize就是选择的每页展示几条数据
            // console.log(pageSize);
            // 更新limit/
            this.limit = pageSize
            console.log(this.limit);
            // 获取用户列表
            this.getUserList()
        },

        //   列表选中状态发生改变的监听回调
        handleSelectionChange(selection) {
            console.log(selection);
            this.selectedIds = selection.map(item => item.id)
            console.log(this.selectedIds);
        },

        // 删除所有选中的用户
        async deleteUsers() {
            // console.log(1);
            let result = await this.$API.user.removeUsers(this.selectedIds)
            // console.log(result);
        },

        // 点击分配角色
        async distribute(row) {
            this.dialoguserFormVisible = true
            this.role.username = row.username
            this.role.id = row.id
            // console.log(this.role);
            let result = await this.$API.user.getRoles(row.id)
            let { allRolesList, assignRoles } = result.data
            this.role.roleList = allRolesList
            this.role.assignRoles = assignRoles
            this.cities = allRolesList
            this.city = allRolesList.map((item) => item.roleName)
            this.checkedCities = assignRoles.map((item) => item.roleName)
        },

        // 分配角色复选框回调
        handleCheckAllChange(val) {
            // console.log(val);
            this.checkedCities = val ? this.city : [];
            this.isIndeterminate = false;
        },
        // 单选
        handleCheckedCitiesChange(value) {
            console.log(value);
            let checkedCount = value.length;
            
            this.checkAll = checkedCount === this.cities.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
        },
        //  点击分配角色对话框的确定按钮
        async save() {
            let arr = this.cities.reduce((pre, cur) => {
                if (this.checkedCities.includes(cur.roleName)) {
                    pre.push(cur.id)
                }
                return pre
            }, [])
            let Arr = arr.join(',')
            let result = await this.$API.user.assignRoles(this.role.id, Arr)
            console.log(result);
            this.dialoguserFormVisible = false
            this.getUserList()
        },
    }
}
</script>

<style scoped>
.head {
    width: 380px;
    display: flex;
    justify-content: space-between;
}

.head .box {
    width: 200px;
}

.center {
    width: 250px;
    margin: 20px 0;
}
</style>